﻿using System;
using System.Collections.Generic;
using System.Text;

using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using System.Linq;
using System.Collections;

namespace System
{
    public class ArrayJsonConverter : JsonConverter
    {
        private readonly Type type;
        public ArrayJsonConverter() : this(typeof(string))
        {

        }

        public ArrayJsonConverter(Type type)
        {
            this.type = type;
        }
        public override bool CanConvert(Type objectType)
        {
            return objectType.IsEquivalentTo(this.type);
        }
        private string CharTranslation(string text)
        {
            return text.Replace(",", "&cm;");
        }

        private string TranslationForChar(string text)
        {
            return text.Replace("&cm;", ",");
        }

        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            try
            {
                IEnumerable arr = serializer.Deserialize(reader, typeof(List<>).MakeGenericType(type)) as IEnumerable;
                if (arr == null)
                    return null;
                var list = new List<string>();
                foreach (var item in arr)
                {
                    list.Add(CharTranslation(item.ToString()));
                }
                return string.Join(",", list);
            }
            catch (Exception)
            {
                throw new JsonReaderException("不是有效的数组类型");
            }
        }

        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            try
            {
                var strs = value.ToString().Split(',', StringSplitOptions.RemoveEmptyEntries);
                Array array = Array.CreateInstance(type, strs.Length);
                for (int i = 0; i < strs.Length; i++)
                {
                    var str = TranslationForChar(strs[i]);
                    if (type.IsInstanceOfType(str))
                        array.SetValue(str, i);
                    else if (str == "")
                        array.SetValue(null, i);
                    else
                        array.SetValue(Convert.ChangeType(str, type), i);
                }
                serializer.Serialize(writer, array);
            }
            catch (Exception e)
            {
                serializer.Serialize(writer, "转换失败：" + e.Message);
            }
        }
    }
}
